package com.huan.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "UserLoginFilter", urlPatterns = {"/index.jsp"})
public class UserLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println(this.getClass().getName() + "................");
        String LoginUser = null;

        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            // if 登录成功
            Object object = req.getSession().getAttribute("userCode");
            if (object instanceof String) {
                LoginUser = (String) object;
            }
            if (LoginUser != null && !"".equals(LoginUser)) {
                chain.doFilter(request, response);
            } else {// else 未成功
                //forword to index0.jsp
                req.getRequestDispatcher("login.jsp").forward(request, response);
            }
        }
    }
}
